//
//  YLATalk5ViewController.swift
//  Your Lover AI
//
//  Created by 阿忠 on 2024/7/8.
//

import Foundation
import UIKit
import Alamofire
import CryptoKit
import SCrypto
import SwiftyJSON
import SDWebImage
import CryptoSwift
import PopupDialog
import SVProgressHUD
import AdSupport
import GoogleMobileAds

class YLATalk5ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate, GADFullScreenContentDelegate{
    
    var tableView : UITableView!
    private let AncientBookCellID = "YLATalkLeftCell"
    var dataStr: String!//heard里面的
    var dataBody: String!//body里面的
    var gainStr: String!//获取里面的
    var roleId: String!//机器人ID
    var roleName: String!//机器人名字
    var roleCoverUrl: String!//机器人图片
    
    var Role_date: [[String: String]] = []
    
    var Role_List: [[String: String]] = []
    
    var isUserStroe = false
    
    let buttondata = ["Can I kiss you","Hello my sweetheart","Kiss your body","I love you","Touch your body","Take a shower together","Your eyes are so beautiful"]
    
    var isScrollToBottom = false
    
    var nameView: YLATostStroeView! = nil
    var blurEffectView: UIVisualEffectView! = nil
    var rewardedView: YLARewardedView! = nil
    
    //激励视频
    var rewardedAd: GADRewardedAd?
    
    lazy var bgImg: UIImageView = {
        let image = UIImageView(image: UIImage(named: "chat_bg"))
        image.sd_setImage(with: URL(string: roleCoverUrl!), placeholderImage: UIImage(named: "chat_default"))
        image.contentMode = .scaleAspectFill
        image.layer.masksToBounds = true
        return image
    }()
    
    lazy var backBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .clear
        button.setImage(UIImage(named: "icon_left"), for: UIControl.State.normal)
        button.addTarget(self, action: #selector(backClick), for: .touchUpInside)
        return button
    }()
    
    lazy var nameLb: UILabel = {
        let lab = UILabel()
        lab.text = self.roleName
        lab.textColor = .white
        lab.font = UIFont.systemFont(ofSize: 18)
        lab.textAlignment = .left
        lab.numberOfLines = 0
        return lab
    }()
    
    lazy var msgsLb: UILabel = {
        let lab = UILabel()
        lab.text = "Msgs:"
        lab.textColor = .white
        lab.font = UIFont.systemFont(ofSize: 11)
        lab.textAlignment = .left
        lab.numberOfLines = 0
        return lab
    }()
    
    lazy var numberLb: UILabel = {
        let lab = UILabel()
        let userDefaults = UserDefaults.standard
//        self.isUserStroe = userDefaults.bool(forKey: "isUserStroe")
        self.isUserStroe = userDefaults.bool(forKey: "life") || userDefaults.bool(forKey: "year") ||  userDefaults.bool(forKey: "week")
        if self.isUserStroe {
            lab.text = "max"
        }else{
            let isUserFreeCount = userDefaults.integer(forKey: "isUserFreeCount")
            let string = String(format: "%d", isUserFreeCount)
            lab.text = string
        }
        
        lab.textColor = UIColor(hex: "FCDBA4")
        lab.font = UIFont.systemFont(ofSize: 11)
        lab.textAlignment = .left
        lab.numberOfLines = 0
        return lab
    }()
    
    lazy var vipBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .clear
        button.setImage(UIImage(named: "nav_vip 1"), for: UIControl.State.normal)
        button.addTarget(self, action: #selector(vipClick), for: .touchUpInside)
        return button
    }()
    
    lazy var stimulateBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .clear
        button.setImage(UIImage(named: "nav_video"), for: UIControl.State.normal)
        button.addTarget(self, action: #selector(stimulateClick), for: .touchUpInside)
        return button
    }()
    
    lazy var bottonVc: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
    lazy var enterVc: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: "551EC2")
        return view
    }()
    
    lazy var enterTf: UITextField = {
        let tfd = UITextField()
        tfd.delegate  = self
        tfd.borderStyle = .none
        tfd.placeholder = "  Enter conversation content"
        tfd.textAlignment = .left
        tfd.delegate = self
        tfd.keyboardType = .default
        tfd.backgroundColor = UIColor(hex: "7157FF")
        tfd.layer.cornerRadius = 10
        tfd.layer.masksToBounds = true
        return tfd
    }()
    
    //发送
    lazy var sendBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .clear
        button.setImage(UIImage(named: "chat_send"), for: .normal)
        button.addTarget(self, action: #selector(sendClick), for: .touchUpInside)
        return button
    }()
    
    let scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.isScrollEnabled = true
        scrollView.backgroundColor = .clear
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.isPagingEnabled = true // 如果你想要分页效果
        return scrollView
      }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.red
        
        setData()
        setUI()
        //首次进入  默认请求图片
        if self.Role_date.count == 1 {
            setRequest("picture")
        }
     
//        DispatchQueue.main.async {
//
//          // Initialize the Google Mobile Ads SDK.
//          GADMobileAds.sharedInstance().start()
//
//        }

       
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        self.tabBarController!.tabBar.isHidden = true
                
        let userDefaults = UserDefaults.standard
//        self.isUserStroe = userDefaults.bool(forKey: "isUserStroe")
        self.isUserStroe = userDefaults.bool(forKey: "life") || userDefaults.bool(forKey: "year") ||  userDefaults.bool(forKey: "week")
        if self.isUserStroe {
            self.numberLb.text = "max"
        }else{
            let isUserFreeCount = userDefaults.integer(forKey: "isUserFreeCount")
            let string = String(format: "%d", isUserFreeCount)
            self.numberLb.text = string
        }
        print(isUserStroe)
        self.tableView.reloadData()
        

        
//        Task {
//          await loadRewardedAd()
//        }
      
    }
    
    func setData(){
        // 从UserDefaults中检索Data
        if let retrievedData = UserDefaults.standard.data(forKey: "Roleid5"),
            let retrievedArray = try? PropertyListDecoder().decode([[String: String]].self, from: retrievedData) {

            
            self.Role_date = retrievedArray
            

        }
        if let retrievedList = UserDefaults.standard.data(forKey: "RoleidList"),
            let retrievedList = try? PropertyListDecoder().decode([[String: String]].self, from: retrievedList) {
            
            self.Role_List = retrievedList

        }
    }
    
    func setUI() {
        
        view.addSubview(bgImg)
        bgImg.snp.makeConstraints { make in
            make.left.top.bottom.right.equalToSuperview()
        }
        
        view.addSubview(backBtn)
        backBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(50)
            make.width.height.equalTo(32)
        }
        
        view.addSubview(nameLb)
        nameLb.snp.makeConstraints { make in
            make.left.equalTo(backBtn.snp.right).offset(4)
            make.top.equalTo(backBtn)
        }
        
        view.addSubview(msgsLb)
        msgsLb.snp.makeConstraints { make in
            make.left.equalTo(nameLb)
            make.top.equalTo(nameLb.snp.bottom).offset(2)
        }
        
        view.addSubview(numberLb)
        numberLb.snp.makeConstraints { make in
            make.left.equalTo(msgsLb.snp.right)
            make.centerY.equalTo(msgsLb)
        }
        

        view.addSubview(vipBtn)
        vipBtn.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.centerY.equalTo(backBtn)
            make.width.height.equalTo(36)
        }
        
        let userDefaults = UserDefaults.standard
        stimulateBtn.isHidden = userDefaults.bool(forKey: "life") || userDefaults.bool(forKey: "year") ||  userDefaults.bool(forKey: "week")
        view.addSubview(stimulateBtn)
        stimulateBtn.snp.makeConstraints { make in
            make.right.equalTo(vipBtn.snp.left).offset(-14)
            make.centerY.equalTo(vipBtn)
            make.width.height.equalTo(36)
        }
        
        view.addSubview(bottonVc)
        bottonVc.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(115)
        }
        
        bottonVc.addSubview(enterVc)
        enterVc.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(70)
        }

        enterVc.addSubview(enterTf)
        enterTf.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-66.5)
            make.height.equalTo(43.5)
            make.centerY.equalToSuperview()
        }
        
        bottonVc.addSubview(sendBtn)
        sendBtn.snp.makeConstraints { make in
            make.left.equalTo(enterTf.snp.right).offset(11.5)
            make.centerY.equalTo(enterTf)
            make.width.equalTo(43)
            make.height.equalTo(43)
        }
        
        bottonVc.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(enterVc.snp.top)
        }
        
        let buttonCount = 6
                let buttonWidth: CGFloat = 160 // 假设每个按钮的宽度是 100 点
                let buttonSpacing: CGFloat = 10 // 按钮之间的间距

                var xPosition: CGFloat = 0

        
                for i in 0..<buttonCount {
                    let button = UIButton(type: .system)
                    button.setTitle(buttondata[i], for: .normal)
                    button.backgroundColor = .clear // 只是为了示例，你可以设置为你想要的颜色
                    button.setTitleColor(.white, for: .normal)
                    button.layer.cornerRadius = 10
                    button.layer.borderWidth = 1
                    button.layer.borderColor = UIColor.white.cgColor
                    button.layer.masksToBounds = true
                    button.tag = 10000 + i
                   
                    button.addTarget(self, action: #selector(touchClick(_:)), for: .touchUpInside)
                    scrollView.addSubview(button)
                    button.snp.makeConstraints { make in
                        make.left.equalTo(xPosition)
                        make.centerY.equalToSuperview()
                        make.height.equalTo(31)
                        make.width.equalTo(buttonWidth)
                    }

                    xPosition += buttonWidth + buttonSpacing
                }

                // 设置 scrollView 的 contentSize 以适应所有按钮
                scrollView.contentSize = CGSize(width: xPosition - buttonSpacing, height: scrollView.frame.height)
        
        tableView = UITableView()
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 10
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(backBtn.snp.bottom).offset(20)
            make.bottom.equalTo(bottonVc.snp.top)
        }
        view.addSubview(tableView)
        tableView.dataSource = self
        tableView.delegate = self
        extendedLayoutIncludesOpaqueBars = true;
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false;
        };
        
        //隐藏剩余次数提示
        msgsLb.isHidden = false
        numberLb.isHidden = false
        
        tableView.reloadData()
        
    }
    
    
    //MARK: UITableViewDataSource
    // cell的个数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.Role_date.count
    }
    // UITableViewCell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let dict:Dictionary = self.Role_date[indexPath.row]
        let msgType = dict["msgType"]
        if msgType == "1"{//机器人文本
            let cellid = "testCellID"
            var cell:YLATalkLeftCell? = tableView.dequeueReusableCell(withIdentifier: cellid) as? YLATalkLeftCell
            if cell==nil {
                cell = YLATalkLeftCell(style:.subtitle, reuseIdentifier: cellid)
                
            }
            cell?.backgroundColor = .clear
            cell?.selectionStyle = .none
            cell?.timeLab.text = dict["time"]
            let content = dict["msgContent"]
            cell?.contentLab.text = ""
            cell?.contentLab.attributedText = attributedString(withString: content!, font: .systemFont(ofSize: 15), textColor: .white, lineSpacing: 5, wordSpacing: 1.5)
            cell?.iconImg.sd_setImage(with: URL(string: self.roleCoverUrl), placeholderImage: UIImage(named: "logo"))
            return cell!
        }else if msgType == "2" {//机器人图片
            let cellid = "testCellID"
            var cell:YLATalkImageCell? = tableView.dequeueReusableCell(withIdentifier: cellid) as? YLATalkImageCell
            if cell==nil {
                cell = YLATalkImageCell(style:.subtitle, reuseIdentifier: cellid)
                
            }
            cell?.backgroundColor = .clear
            cell?.selectionStyle = .none
            let CoverUrl = dict["msgContent"]
            cell?.videoImg.sd_setImage(with: URL(string: CoverUrl!), placeholderImage: UIImage(named: "chat_default"))
            cell?.iconImg.sd_setImage(with: URL(string: self.roleCoverUrl), placeholderImage: UIImage(named: "logo"))
            cell?.timeLab.text = dict["time"]
            if self.isUserStroe {
                cell?.playImg.isHidden = true
            }else{
                cell?.playImg.isHidden = false
            }
            return cell!
        }else if msgType == "3"{//机器人视频
            let cellid = "testCellID"
            var cell:YLAVideoCell? = tableView.dequeueReusableCell(withIdentifier: cellid) as? YLAVideoCell
            if cell==nil {
                cell = YLAVideoCell(style:.subtitle, reuseIdentifier: cellid)
                
            }
            cell?.backgroundColor = .clear
            cell?.selectionStyle = .none
            cell?.iconImg.sd_setImage(with: URL(string: self.roleCoverUrl), placeholderImage: UIImage(named: "logo"))
            
            return cell!
        }else if msgType == "4"{//用户发送的信息
            let cellid = "testCellID"
            var cell:YLARightCell? = tableView.dequeueReusableCell(withIdentifier: cellid) as? YLARightCell
            if cell==nil {
                cell = YLARightCell(style:.subtitle, reuseIdentifier: cellid)
                
            }
            cell?.timeLab.text = dict["time"]
            let content = dict["msgContent"]
//            cell?.contentLab.attributedText = content!.attributedString(font: .systemFont(ofSize: 15), textColor: .white, lineSpaceing: 5, wordSpaceing: 1.5)
            cell?.contentLab.attributedText = attributedString(withString: content!, font: .systemFont(ofSize: 15), textColor: .white, lineSpacing: 5, wordSpacing: 1.5)
            cell?.backgroundColor = .clear
            cell?.selectionStyle = .none
            return cell!
        }else{
            let cellid = "testCellID"
            var cell:YLALodaingCell? = tableView.dequeueReusableCell(withIdentifier: cellid) as? YLALodaingCell
            if cell==nil {
                cell = YLALodaingCell(style:.subtitle, reuseIdentifier: cellid)
                
            }
            cell?.iconImg.sd_setImage(with: URL(string: self.roleCoverUrl), placeholderImage: UIImage(named: "logo"))
            cell?.timeLab.text = dict["time"]
            let content = dict["msgContent"]
            cell?.backgroundColor = .clear
            cell?.selectionStyle = .none
            return cell!
        }
 
    }
    
    
    //MARK: UITableViewDelegate
    // 设置cell高度
//    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        return 130
//    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if !isScrollToBottom {
            self.tableView.scrollToRow(at: IndexPath(row: self.Role_date.count - 1, section: 0), at: .none, animated: false)
                
                if indexPath.row == self.Role_date.count - 1 {
                    isScrollToBottom = true
                }
            }
    }
    // 选中cell后执行此方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
      print("------选中了chat的cell------")
        let dict:Dictionary = self.Role_date[indexPath.row]
        let msgType = dict["msgType"]
        if msgType == "2"{//机器人文本
            let userDefaults = UserDefaults.standard
//            self.isUserStroe = userDefaults.bool(forKey: "isUserStroe")
            self.isUserStroe = userDefaults.bool(forKey: "life") || userDefaults.bool(forKey: "year") ||  userDefaults.bool(forKey: "week")
            if !self.isUserStroe {
                //弹窗引导用户去开通会员
                self.tostStroeView(type: "2")
                return
            }else{
                //判断是否是周会员
//                let storeType = userDefaults.string(forKey: "stroeType")
//                if storeType == "week" {
//                    
//                    let userDefaults = UserDefaults.standard
//                    var isUserFreeCount = userDefaults.integer(forKey: "storeWeekCont")
//                    if isUserFreeCount > 0 {
//                        isUserFreeCount -= 1
//                        userDefaults.set(isUserFreeCount, forKey: "storeWeekCont")
//                        let imageVc = YLATalkImageViewController()
//                        imageVc.roleCoverUrl = dict["msgContent"]
//                        self.navigationController?.pushViewController(imageVc, animated: true)
//                    }else{
//                        self.tostStroeView(type: "3")
//                    }
//                   
//                    
//                }else{
//                    let imageVc = YLATalkImageViewController()
//                    imageVc.roleCoverUrl = dict["msgContent"]
//                    self.navigationController?.pushViewController(imageVc, animated: true)
//                }
                let storeType = userDefaults.bool(forKey: "life") || userDefaults.bool(forKey: "year")
                if !storeType {

                    let userDefaults = UserDefaults.standard
                    var isUserFreeCount = userDefaults.integer(forKey: "storeWeekCont")
                    if isUserFreeCount > 0 {
                        isUserFreeCount -= 1
                        userDefaults.set(isUserFreeCount, forKey: "storeWeekCont")
                        let imageVc = YLATalkImageViewController()
                        imageVc.roleCoverUrl = dict["msgContent"]
                        self.navigationController?.pushViewController(imageVc, animated: true)
                    }else{
                        self.tostStroeView(type: "3")
                    }
                    
                }else{
                    
                    let imageVc = YLATalkImageViewController()
                    imageVc.roleCoverUrl = dict["msgContent"]
                    self.navigationController?.pushViewController(imageVc, animated: true)
                }
            }
            
        }
        
    }
    
    func getCurrentTimestampMilliseconds() -> Int64 {
        let date = Date()
        let timeInterval = date.timeIntervalSince1970
        return Int64(timeInterval * 1000)
    }
    
    func encrypt(text: String, key: SymmetricKey) -> Data {
        let data = text.data(using: .utf8)!
        let sealedBox = try! AES.GCM.seal(data, using: key)
        return sealedBox.combined!
    }
    
    func dataToHexString(_ data: Data) -> String {
        let hexChars = "0123456789ABCDEF"
        var hexString = ""
        
        for byte in data {
            hexString += String(format: "%02x", byte)
        }
        
        return hexString
    }
    
    @objc func backClick(){
        
        self.navigationController?.popViewController(animated: false)
    }
    
    @objc func vipClick(){
        let vipVc = YLAStroeViewControll()
        self.navigationController?.pushViewController(vipVc, animated: true)
    }
    
    @objc func stimulateClick(){
        print("--------激励广告----------")

//        if let ad = rewardedAd {
//          ad.present(fromRootViewController: self) {
//            let reward = ad.adReward
//            print("Reward received with currency \(reward.amount), amount \(reward.amount.doubleValue)")
////                self.earnCoins(NSInteger(truncating: reward.amount))
//            // TODO: Reward the user.
//          }
//        } else {
//          let alert = UIAlertController(
//            title: "Rewarded ad isn't available yet.",
//            message: "The rewarded ad cannot be shown at this time",
//            preferredStyle: .alert)
//          let alertAction = UIAlertAction(
//            title: "OK",
//            style: .cancel)
//          alert.addAction(alertAction)
//          self.present(alert, animated: true, completion: nil)
//        }
        
        self.tostRewardedView()
        
        

    }
    
    func loadRewardedAd() async {
      do {
        rewardedAd = try await GADRewardedAd.load(
          withAdUnitID: "ca-app-pub-3940256099942544/1712485313", request: GADRequest())
        rewardedAd?.fullScreenContentDelegate = self
      } catch {
        print("Rewarded ad failed to load with error: \(error.localizedDescription)")
      }
    }
    
    // MARK: GADFullScreenContentDelegate

    func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
      print("即将播放广告")
    }

    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
      print("看完广告  获取奖励")
    }
    
    
    @objc func sendClick(){
        //如果没有输入提示用户
        if let text = enterTf.text, !text.isEmpty {
            setRequest(self.enterTf.text!)
            self.enterTf.text = ""
                    print("输入的字符不为空")
                } else {
                    print("输入的字符为空")
                    let popup = PopupDialog(title: "Notice", message: "Please enter information", image: nil)
                    self.present(popup, animated: true, completion: nil)
                    return
                }
        
    }

    
    @objc func touchClick(_ sender: UIButton) {
          // 使用按钮的tag值来区分不同的按钮
          switch sender.tag {
          case 10000:
              setRequest(self.buttondata[0])
          case 10001:
              setRequest(self.buttondata[1])
          case 10002:
              setRequest(self.buttondata[2])
          case 10003:
              setRequest(self.buttondata[3])
          case 10004:
              setRequest(self.buttondata[4])
          case 10005:
              setRequest(self.buttondata[5])

          // ...
          default:
              print("Button \(sender.tag) clicked with title: \(sender.title(for: .normal) ?? "Unknown")")
          }
      }
    
    func tostRewardedView() {
        let blurEffect = UIBlurEffect(style: .light) // 可调整模糊效果的样式
        self.blurEffectView = UIVisualEffectView(effect: blurEffect)
        self.blurEffectView.frame = self.view.bounds
        self.view.addSubview(self.blurEffectView)
        
        let dialogFrame = CGRect(x: 0, y: 200, width: 270, height: 200)
        self.rewardedView = YLARewardedView(frame: dialogFrame, title: "续费", paymentMethod: "支付宝", paymentDescription: "请使用支付宝完成支付。")
        
        self.view.addSubview(self.rewardedView)
        self.rewardedView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.left.equalTo(43)
            make.right.equalTo(-43)
            make.height.equalTo(254)
        }
        
        self.view.insertSubview(self.blurEffectView, belowSubview: self.rewardedView)
        
        self.rewardedView.onCancel = {
            // 执行取消操作
            self.rewardedView.removeFromSuperview()
            self.blurEffectView.removeFromSuperview()
        }

        rewardedView.onConfirm = { [self] text in
            if let password = text {
                print("您输入的支付密码是：\(password)")
                //存储新的激励视频剩余次数
                let userDefaults = UserDefaults.standard
                var isUserFreeCount = userDefaults.integer(forKey: "isWatchCount")
                isUserFreeCount -= 1
                userDefaults.set(isUserFreeCount, forKey: "isWatchCount")
                
                AppRewardedManager.shared.showAdIfAvailable()
                
                var isUserFreeCounts = userDefaults.integer(forKey: "isUserFreeCount")
                isUserFreeCounts += 3
                let string = String(format: "%d", isUserFreeCounts)
                self.numberLb.text = string
                //存储新的免费次数
                userDefaults.set(isUserFreeCounts, forKey: "isUserFreeCount")
                
                self.rewardedView.removeFromSuperview()
                self.blurEffectView.removeFromSuperview()
                
               
                
            } else {
                print("取消了输入")
            }
        }
      
    }
    
    func tostStroeView(type:String) {
        let blurEffect = UIBlurEffect(style: .light) // 可调整模糊效果的样式
        self.blurEffectView = UIVisualEffectView(effect: blurEffect)
        self.blurEffectView.frame = self.view.bounds
        self.view.addSubview(self.blurEffectView)
        
        let dialogFrame = CGRect(x: 0, y: 200, width: 270, height: 200)
        self.nameView = YLATostStroeView(frame: dialogFrame, title: "续费", paymentMethod: "支付宝", paymentDescription: "请使用支付宝完成支付。")
        if type == "1"{
            self.nameView.contentLabel.text = "Your number of conversations has been exhausted. It is recommended that you upgrade to an annual membership to enjoy unlimited chats."
        }else if type == "2"{
            self.nameView.contentLabel.text = "If you want to view exciting pictures or videos, please become a valued subscriber"
        }else if type == "3"{
            self.nameView.contentLabel.text = "The number of pictures or videos you can view has been used up. If you want to continue to view pictures or videos, it is recommended that you upgrade to an annual membership."
        }
        
        self.view.addSubview(self.nameView)
        self.nameView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.left.equalTo(43)
            make.right.equalTo(-43)
            make.height.equalTo(254)
        }
        
        self.view.insertSubview(self.blurEffectView, belowSubview: self.nameView)
        
        self.nameView.onCancel = {
            // 执行取消操作
            self.nameView.removeFromSuperview()
            self.blurEffectView.removeFromSuperview()
        }

        nameView.onConfirm = { [self] text in
            if let password = text {
                print("您输入的支付密码是：\(password)")
               
                let stroeVc = YLAStroeViewControll()
                self.navigationController?.pushViewController(stroeVc, animated: true)
                self.nameView.removeFromSuperview()
                self.blurEffectView.removeFromSuperview()
                
            } else {
                print("取消了输入")
            }
        }
      
    }
    
    //发动信息
    func setRequest(_ string: String) {
        
        //先判断是否是会员
        let userDefaults = UserDefaults.standard
//        self.isUserStroe = userDefaults.bool(forKey: "isUserStroe")
        self.isUserStroe = userDefaults.bool(forKey: "life") || userDefaults.bool(forKey: "year") ||  userDefaults.bool(forKey: "week")
        if !self.isUserStroe {
            //判断还有没有剩余次数
            var isUserFreeCount = userDefaults.integer(forKey: "isUserFreeCount")
            if isUserFreeCount <= 0 {
                //弹窗引导用户去开通会员
                self.tostStroeView(type: "1")
                return
            }
        }
        
//        var uuid = ASIdentifierManager.shared().advertisingIdentifier.uuidString
        let uuid = KeychainManager.shared.retrieveUUID()!
        let userInfo: [String: Any] = [
            "userId": uuid,
            "userType": "1",
            "deviceType": "2"
        ]
        var firstSend = "0"
//        if self.Role_date.count == 1 {
//            firstSend = "1"
//        }else{
//            firstSend = "0"
//        }
        let msgId = self.currentTimeStampWithRandomLetters()
        let bodyInfo: [String: Any] = [
            "msgContext": string,
            "msgId": msgId,
            "firstSend": firstSend,
            "userId": uuid,
            "robotRoleId": self.roleId
        ]
        
        do {

            let userData = try JSONSerialization.data(withJSONObject: userInfo, options: [])
            let bodyData = try JSONSerialization.data(withJSONObject: bodyInfo, options: .prettyPrinted)
            let userString = String(data: userData, encoding: .utf8)
            let bodyString = String(data: bodyData, encoding: .utf8)
             
            let key = "jDx9m33EHmzUXI9D"
            print("key密钥：\(key)")
             
            //使用AES-128-ECB加密模式
            let aes = try AES(key: key.bytes, blockMode: ECB())
             
            //开始加密
            let userpted = try aes.encrypt(userString!.bytes)
            let encrypted = try aes.encrypt(bodyString!.bytes)
            let userptedBase64 = userpted.toHexString() //将加密结果转成hex形式
            let encryptedBase64 = encrypted.toHexString() //将加密结果转成hex形式
            dataStr = userptedBase64
            dataBody = encryptedBase64
            print("加密结果(tou)：\(userptedBase64)")
            print("加密结果(body)：\(encryptedBase64)")
            
        } catch { }
 

        
        
        let headers: HTTPHeaders = [
            "accept-encoding" : "gzip",
            "connection" : "Keep-Alive",
            "content-length" : "45",
            "Content-Type": "application/json",
            "data" : dataStr,
            "user-agent": "okhttp/4.10.0"
        ]
        
        let timestampMilliseconds = getCurrentTimestampMilliseconds()
        let parameters = [
            "productId": "2",
            "timestamp": timestampMilliseconds,
            "data" : dataBody
        ] as [String : Any]
      
//        Alamofire.request(YLARequest().sendMsgUrl, method: .post, parameters: parameters,encoding: JSONEncoding.default,headers: headers).responseJSON { response in
//            switch response.result {
//            case .success(let value):
//                let json = JSON.init(value)
//                
//                if json["code"].intValue == 200 {
//                    //收起键盘
//                    self.enterTf.resignFirstResponder()
//                    
//                   
//                    
//                    //成功的时候要将用户的发动添加到数组
//                    //如果是第一次默认索要图片  不添加
//                    if self.Role_date.count != 1{
//                        let time = self.currentMonthDayHourMinuteString()
//                        let enter = string
//                        let Roledata =
//                        ["coverUrl":self.roleCoverUrl,"name":self.roleName,"roleId":"18615782958","msgType":"4","msgContent":enter,"time":time] as [String : String]
//                        self.Role_date.append(Roledata as! [String : String])
//                        // 将字典数组编码为Data
//                        let encodedData = try? PropertyListEncoder().encode(self.Role_date)
//
//                        // 使用UserDefaults存储Data
//                        UserDefaults.standard.set(encodedData, forKey: "Roleid5")
//                        
//                        //如果不是会员  免费次数减1
//                        let userDefaults = UserDefaults.standard
////                        self.isUserStroe = userDefaults.bool(forKey: "isUserStroe")
//                        self.isUserStroe = userDefaults.bool(forKey: "life") || userDefaults.bool(forKey: "year") ||  userDefaults.bool(forKey: "week")
//                        if !self.isUserStroe {
//                            var isUserFreeCount = userDefaults.integer(forKey: "isUserFreeCount")
//                            isUserFreeCount -= 1
//                            let string = String(format: "%d", isUserFreeCount)
//                            self.numberLb.text = string
//                            //存储新的免费次数
//                            userDefaults.set(isUserFreeCount, forKey: "isUserFreeCount")
//                        }
//                    }
//                    
//                    
//                    //模拟在请求数据
//                    let time = self.currentMonthDayHourMinuteString()
//                    let enter = string
//                    let Roledata =
//                    ["coverUrl":self.roleCoverUrl,"name":self.roleName,"roleId":"18615782958","msgType":"5","msgContent":enter,"time":time] as [String : String]
//                    self.Role_date.append(Roledata as! [String : String])
//                    self.tableView.reloadData()
//                    
//                    self.tableView.scrollToRow(at: IndexPath(row: self.Role_date.count - 1, section: 0), at: .none, animated: false)
//                    
//                    let data = json["data"]
//                    let jsonObj = JSON.init(data)
//                    //判断是否正确拿到信息 还是要调用获取接口
//                    let msgState = jsonObj["msgState"].stringValue
//                    if msgState == "1"{//同步返回
//                        
//                        //先删除数组中最后一个
//                        self.Role_date.removeLast()
//                        self.tableView.reloadData()
//                        
//                        self.tableView.scrollToRow(at: IndexPath(row: self.Role_date.count - 1, section: 0), at: .none, animated: false)
//
//                        //将数据添加到数组
//                        let msgType = jsonObj["msgType"].stringValue
//                        let msgContent = jsonObj["msgContent"].stringValue
//                        let time = self.currentMonthDayHourMinuteString()
//                        let Roledata =
//                        ["coverUrl":self.roleCoverUrl,"name":self.roleName,"roleId":"1","msgType":msgType,"msgContent":msgContent,"time":time,"roleIdind":"5"] as [String : String]
//                        self.Role_date.append(Roledata as! [String : String])
//                        // 将字典数组编码为Data
//                        let encodedData = try? PropertyListEncoder().encode(self.Role_date)
//
//                        // 使用UserDefaults存储Data
//                        UserDefaults.standard.set(encodedData, forKey: "Roleid5")
//                        
//                        //添加到聊天记录数组
//                        if self.Role_date.count > 2 {
//                            //如果聊天记录数组没有 直接添加
//                            var isRoleInt = 0  //用来表示是否有此机器人的信息
//                            //根据标识删除数组内消息  再将新的消息添加到第一个
//                            for i in 0..<self.Role_List.count {
//                                let dict:Dictionary = self.Role_List[i]
//                                let roleIding = dict["roleIdind"]
//                                if roleIding == "5"{
//                                    isRoleInt = 1
//                                    self.Role_List.remove(at: i)
//                                    self.Role_List.insert(Roledata, at: 0)
//                                    let encodedList = try? PropertyListEncoder().encode(self.Role_List)
//                                    
//                                    // 使用UserDefaults存储Data
//                                    UserDefaults.standard.set(encodedList, forKey: "RoleidList")
//                                }
//                            }
//                            if isRoleInt == 0 {
//                                self.Role_List.insert(Roledata, at: 0)
//                                let encodedData = try? PropertyListEncoder().encode(self.Role_List)
//
//                                // 使用UserDefaults存储Data
//                                UserDefaults.standard.set(encodedData, forKey: "RoleidList")
//                            }
//                            if self.Role_List.count == 0 {
//                                self.Role_List.insert(Roledata, at: 0)
//                                let encodedData = try? PropertyListEncoder().encode(self.Role_List)
//
//                                // 使用UserDefaults存储Data
//                                UserDefaults.standard.set(encodedData, forKey: "RoleidList")
//                            }
//                        }
//
//                        self.tableView.reloadData()
//                        self.tableView.scrollToRow(at: IndexPath(row: self.Role_date.count - 1, section: 0), at: .none, animated: false)
//                    }else{//调用接口
////                        self.setGainRequest(string, msgId: msgId)
//                        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
//                            self.setGainRequest(string, msgId: msgId)
//                        }
//                    }
//
//                    
//                        }
//              else {
//                    print("Invalid JSON format or missing 'data' field")
//                }
//            case .failure(let error):
//                // 请求失败，处理错误信息
//                print("Error: \(error)")
//            }
//        }
    }
    
    
    //获取信息
    func setGainRequest(_ string: String, msgId:String){
        
//        var uuid = ASIdentifierManager.shared().advertisingIdentifier.uuidString
        let uuid = KeychainManager.shared.retrieveUUID()!
        let gainInfo: [String: Any] = [
            "msgId": msgId,
            "robotRoleId": self.roleId,
            "userId": uuid
        ]
      
        do {

            let gainData = try JSONSerialization.data(withJSONObject: gainInfo, options: .prettyPrinted)
            let gainString = String(data: gainData, encoding: .utf8)
             
            let key = "jDx9m33EHmzUXI9D"
            print("key密钥：\(key)")
             
            //使用AES-128-ECB加密模式
            let aes = try AES(key: key.bytes, blockMode: ECB())
             
            //开始加密
            let gainpted = try aes.encrypt(gainString!.bytes)
            let gainHex = gainpted.toHexString() //将加密结果转成hex形式
            gainStr = gainHex
            print("加密结果(tou)：\(gainStr)")
        } catch { }
        
        let requsetUrl = YLARequest().exchangeGiftUrl + "productId=2&data=" + gainStr
//        Alamofire.request(requsetUrl, method: .get, parameters: nil,encoding: JSONEncoding.default,headers: nil).responseJSON { response in
//            switch response.result {
//            case .success(let value):
//                let json = JSON.init(value)
//                if json["code"].intValue == 200 {
//                    let data = json["data"]
//                    let jsonObj = JSON.init(data)
//                    //判断是否正确拿到信息 还是要调用获取接口
//                    let msgState = jsonObj["msgState"].stringValue
//                    if msgState == "1"{//同步返回
//                        
//                        //先删除数组中最后一个
//                        self.Role_date.removeLast()
//                        self.tableView.reloadData()
//                        
//                        self.tableView.scrollToRow(at: IndexPath(row: self.Role_date.count - 1, section: 0), at: .none, animated: false)
//                        
//                        //将数据添加到数组
//                        let msgType = jsonObj["msgType"].stringValue
//                        let msgContent = jsonObj["msgContent"].stringValue
//                        let time = self.currentMonthDayHourMinuteString()
//                        let Roledata =
//                        ["coverUrl":self.roleCoverUrl,"name":self.roleName,"roleId":"1","msgType":msgType,"msgContent":msgContent,"time":time,"roleIdind":"5"] as [String : String]
//                        self.Role_date.append(Roledata as! [String : String])
//                        // 将字典数组编码为Data
//                        let encodedData = try? PropertyListEncoder().encode(self.Role_date)
//
//                        // 使用UserDefaults存储Data
//                        UserDefaults.standard.set(encodedData, forKey: "Roleid5")
//                        
//                        //添加到聊天记录数组
//                        if self.Role_date.count > 2 {
//                            //如果聊天记录数组没有 直接添加
//                            var isRoleInt = 0  //用来表示是否有此机器人的信息
//                            //根据标识删除数组内消息  再将新的消息添加到第一个
//                            for i in 0..<self.Role_List.count {
//                                let dict:Dictionary = self.Role_List[i]
//                                let roleIding = dict["roleIdind"]
//                                if roleIding == "5"{
//                                    isRoleInt = 1
//                                    self.Role_List.remove(at: i)
//                                    self.Role_List.insert(Roledata, at: 0)
//                                    let encodedList = try? PropertyListEncoder().encode(self.Role_List)
//                                    
//                                    // 使用UserDefaults存储Data
//                                    UserDefaults.standard.set(encodedList, forKey: "RoleidList")
//                                }
//                            }
//                            if isRoleInt == 0 {
//                                self.Role_List.insert(Roledata, at: 0)
//                                let encodedData = try? PropertyListEncoder().encode(self.Role_List)
//
//                                // 使用UserDefaults存储Data
//                                UserDefaults.standard.set(encodedData, forKey: "RoleidList")
//                            }
//                            if self.Role_List.count == 0 {
//                                self.Role_List.insert(Roledata, at: 0)
//                                let encodedData = try? PropertyListEncoder().encode(self.Role_List)
//
//                                // 使用UserDefaults存储Data
//                                UserDefaults.standard.set(encodedData, forKey: "RoleidList")
//                            }
//                        }
//
//                        self.tableView.reloadData()
//                        self.tableView.scrollToRow(at: IndexPath(row: self.Role_date.count - 1, section: 0), at: .none, animated: false)
//                    }else{//调用接口
////                        self.setGainRequest(string, msgId: msgId)
//                        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
//                            self.setGainRequest(string, msgId: msgId)
//                        }
//                    }
//                        }
//        
//            case .failure(let error):
//                // 请求失败，处理错误信息
//                print("Error: \(error)")
//            }
//        }


        
    }
    
    //获取当前的时间
    func currentMonthDayHourMinuteString() -> String {
        let dateFormatter = DateFormatter()
        // 设置日期格式，例如："MM月dd日 HH时mm分"
        dateFormatter.dateFormat = "MM.dd HH:mm"
        // 获取当前日期时间
        let now = Date()
        // 格式化日期时间
        let formattedDate = dateFormatter.string(from: now)
        // 返回格式化后的字符串
        return formattedDate
    }
    
    
    func attributedString(withString text: String, font: UIFont, textColor: UIColor, lineSpacing: CGFloat, wordSpacing: CGFloat) -> NSAttributedString {
        
        let style = NSMutableParagraphStyle()
//        style.lineSpacing = lineSpacing
        // 如果您想要设置首行缩进或尾行缩进，可以保留 headIndent 和 tailIndent 的设置
//        style.headIndent = 5
//        style.tailIndent = -5
//        style.firstLineHeadIndent = 10
        style.alignment = .left
        
        // 注意：wordSpacing 在 NSMutableParagraphStyle 中没有直接对应的属性
        // 如果您想要设置单词间距，您可能需要使用其他方法，比如 NSAttributedString 的附加属性
        // 但请注意，标准的 NSAttributedString 不直接支持单词间距的调整
        
        let attributes: [NSAttributedString.Key: Any] = [
            .font: font,
            .foregroundColor: textColor,
            .paragraphStyle: style,
            // 如果您真的需要调整字符间距（不是单词间距），可以使用 .kern
            // .kern: wordSpacing // 这里我们注释掉，因为这不是单词间距
        ]
        
        // 创建一个 NSMutableAttributedString 并设置属性
        let newtext = text + "    "
        let attrStr = NSMutableAttributedString(string: text, attributes: attributes)
        
        // 如果您需要额外的处理来模拟单词间距（比如使用 NSTextAttachment），可以在这里进行
        
        return attrStr
    }

    
    func currentTimeStampWithRandomLetters() -> String {
        
        // 获取当前时间戳（秒），并转换为字符串（固定长度，如果需要）
        let timeStamp = String(format: "%010d", Int(Date().timeIntervalSince1970.rounded()))
        
        // 生成六位随机英文字母
        let letters = String.random(length: 6)
        
        // 将时间戳和随机字母组合起来
        return timeStamp + letters
    }
    
    
}
